package de.hu.wbi.histoner.eval;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.hu.wbi.histoner.HistoNER;
import de.hu.wbi.histoner.HistoneModification;

/**
Copyright 2011,2012 Philippe Thomas
This file is part of histoner.

HistoNer is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.

HistoNer  is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with HistoNer .  If not, see <http://www.gnu.org/licenses/>.
*/

/**
 * Class is used for named entity recognition on the gold-standard data
 * It simply recognizes and normalizes all histone modicications in the annotated data to the Brno nomenclature
 */
public class Predict {

	static String regex;		//File name containing all regular expression
	static String inDir;		//Input Folder (Corpus)
	static String outFile;		//Predicted histone-mods are written to this file
	
	public static void main(String[] args) throws IOException {
		parseArgs(args);
		
		HistoNER histoner = new HistoNER(regex);		//Instantiate  the HistoNer class
		BufferedWriter bw = new BufferedWriter(new FileWriter(new File(outFile)));
		
		for(File file:(new File(inDir)).listFiles()){		//Iterate over all examples in the folder...
			if(file.isFile() && file.toString().endsWith(".txt")){
				String text = "";
				try {
					text= readFile(file);
				} catch (IOException e) {
					e.printStackTrace();
					System.exit(1);
				}
				int pmid = getPMID(file);
				Set<HistoneModification> modifications = histoner.extractHistoneModifications(text);				
								
				for(HistoneModification mod:modifications){
					bw.append(pmid +"\t" +mod.getFrom() +"\t" +mod.getTo() +"\t'" +mod.getEntity() +"'\t" +mod.toBrnoString() +"\n");
				}
			}
		}
		bw.close();
	}
	
	/**
	 * Returns PubMed id from file name; Filename must be /../../pmid.txt
	 * @param file current filename  
	 * @return PubMed identifier
	 */
	private static int getPMID(File file){
		Pattern pmid = Pattern.compile("(/)([1-9][0-9]*)(.txt)");
		Matcher m = pmid.matcher(file.toString());
		
		m.find();
		return Integer.parseInt(m.group(2));		
	}
	
	/**
	 * Reads the content of a file and returns the content..  
	 * @param file from which the content is read
	 * @return Read content
	 * @throws IOException
	 */
	public static String readFile(File file) throws IOException {
		BufferedReader br = new BufferedReader(new FileReader(file));
		String line; 		
		StringBuilder content = new StringBuilder();
		
		while((line=br.readLine()) != null)
			content.append(line +"\n");
		
		br.close();
		
		return content.substring(0, content.length()-1);
	}
	
	/**
	 * Used to parse the main method arguments
	 * @param args Arguments from main method
	 */
	private static void parseArgs(String [] args){
		if(args.length != 6 ){
			printUsage();
			System.exit(1);
		}
			
		for(int i=0; i<args.length; i+=2){
			if(args[i].equals("-r") || args[i].equals("--regex"))
				regex = args[i+1];
			
			else if(args[i].equals("-i") || args[i].equals("--indir"))
				inDir = args[i+1];
			
			else if(args[i].equals("-o") || args[i].equals("--outdir"))
				outFile = args[i+1];
			
			else{
				System.err.println("Unknown option " +args[i]);
				System.exit(1);
			}
		}	
		
		System.err.println("Starting Prediction");
		System.err.println("Using regular expressions from '" +regex +"'");
		System.err.println("Loading files from directory '" +inDir +"'");
		System.err.println("Writing results to '" +outFile +"'");
	}
	
	/**
	 * Prints a simple usage information
	 */
	private static void printUsage() {
        System.err.println(
        		"Evaluates the quality of named entity Recognition" +
        		"Usage:\n" +
        		"Regular expression file [-r,--regex]\n" +
        		"Directory containing data to tag [-i, --indir]\n"+
        		"Writing results to [-o,--outdir]"
        		);		
	}
}